import io
import time

from PIL import Image
import pytesseract

from appium.webdriver.common.appiumby import By
from selenium.webdriver.support.wait import WebDriverWait

from appPage.enter_homepage import EnterHomePage
from utils.driver_utils import DriverUtils

# 注册暂时不能完成,还不会OCR技术验证验证码
class Register:
    # 注册
    def register(self, driver, phone, password, confirm_password):
        driver.find_element(by=By.ID, value="com.tpshop.malls:id/mine_img").click()
        driver.find_element(by=By.ID, value="com.tpshop.malls:id/head_img").click()
        WebDriverWait(driver, 10).until(lambda x: x.find_element(by=By.ID, value="com.tpshop.malls:id/register_tv")).click()
        # time.sleep(3)
        # driver.find_element(by=By.ID, value="com.tpshop.malls:id/register_tv").click()
        WebDriverWait(driver, 10).until(lambda x: x.find_element(by=By.ID, value="com.tpshop.malls:id/phone_num_et")).send_keys(phone)
        # driver.find_element(by=By.ID, value="com.tpshop.malls:id/phone_num_et").send_keys(phone)
        # 截取验证码元素
        element = driver.find_element(By.ID, "com.tpshop.malls:id/random_code_img")
        location = element.location
        size = element.size

        # 截屏并裁剪验证码区域
        screenshot = driver.get_screenshot_as_png()
        image = Image.open(io.BytesIO(screenshot))
        left = location['x']
        top = location['y']
        right = location['x'] + size['width']
        bottom = location['y'] + size['height']
        image = image.crop((left, top, right, bottom))

        # 使用Tesseract OCR识别
        captcha_text = pytesseract.image_to_string(image)
        print("识别的验证码:", captcha_text)

if __name__ == '__main__':
    driver_utils = DriverUtils()
    driver = driver_utils.get_driver()
    # 进入首页
    enter_homepage = EnterHomePage()
    register = Register()

    enter_homepage.enter_homepage(driver)
    register.register(driver, "18888888888", "123456", "123456")
    time.sleep(3)
    driver_utils.quit_driver()




